package com.forg.mvc.core.handle;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import com.alibaba.fastjson.JSON;
import com.forg.mvc.core.RequestContext;
import com.forg.mvc.core.ResponseWraper;
import com.forg.mvc.core.ResultTypeEnum;
import com.forg.mvc.core.annotation.RenderType;
import com.forg.mvc.core.plugin.VelocityPulgin;

public class RequestHandler extends AbstractHandler {

    public RequestHandler(){
        super();
    }
    
    public RequestHandler(Object o,Method m){
        super(o,m);
    }
    
    @Override
    public String toString(){
        return instance + "." + method.getName();
    }
    
    @Override
    @SuppressWarnings("rawtypes")
    public boolean doHandle(){
        
        ResponseWraper response = RequestContext.getResponse();
        
        ResultTypeEnum resultType = ResultTypeEnum.TEXT;
        String tpl = "";
        if(method.isAnnotationPresent(RenderType.class)){
         
            resultType = method.getAnnotation(RenderType.class).type();
            tpl = method.getAnnotation(RenderType.class).tpl();
        }
        
        Object ret= null;
        try {
            ret = method.invoke(instance, new Object[0]);
        } catch (Exception e) {
            resultType= ResultTypeEnum.TEXT;
            ret = e.getMessage();
        }
        
        try {
            PrintWriter writer = response.getResp().getWriter();
            
            switch (resultType) {
            case JSON:
                writer.write(JSON.toJSONString(ret));
                break;
                
            case VELOCITY:
                if(StringUtils.isNotBlank(tpl)){
                    VelocityContext context = null;
                    
                    if(ret instanceof Map){
                        context = VelocityPulgin.getContext((Map)ret);
                    }else{
                        context = VelocityPulgin.getContext();
                        context.put("r", ret);
                    }
                    
                    Template template = VelocityPulgin.getTemplate(tpl);  
                    if(template != null ){
                        template.merge(context, writer);
                    }
                }else{
                    throw new RuntimeException("invaild template name.");
                }
                
                break;
            default:
                
                writer.write(ret.toString());
                break;
            }
            
            
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            
        }
        
        return true;
    }

}
